package com.study.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName: NettyClientHandler
 * @Description:
 * @Date 2024/04/28 13:55
 * @Author songshaoqiu
 **/
public class NettyClientHandler  extends ChannelInboundHandlerAdapter {
    /**
     * 客户端完成连接 服务器后调用该方法：向服务端写数据
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端连接上服务端：ip【"+ctx.channel().remoteAddress()+"】");
        //向服务器端写数据
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello server".getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * 当通道有读事件发生时，调用该方法：读取服务器返回的数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("读取来自服务器:"+ctx.channel()  .remoteAddress()+",消息内容："+buf.toString(StandardCharsets.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        System.out.println("客户端异常");
        ctx.close();
    }
}
